//
//  CountdownButton.swift
//  Kosspot
//
//  Created by 李鑫 on 2025/6/20.
//

import SwiftUI
import ToastUI

struct CountdownButton: View {
    @State private var countdown = 60
    @State private var isCounting = false
    @State private var timer: Timer?
    @Binding var mobile :String
    @State var message :String?

    @State private var showToast = false
    let action: () -> Void
    
    var body: some View {
        Button {
            if mobile.isEmpty {
                showToast = true
                message = "请填写手机号"
                return
            }
            startCountdown()
            action()
        } label: {
            Text(isCounting ? "\(countdown)s后重试" : "获取验证码")
                .frame(width: 120, height: 40)
                .foregroundColor(Color (hex: "#00C4C4"))
                .font(.system(size: 16))
        }
        .background(Color(hex: "#F5F6FA"))
        .onChange(of: message) {
            newValue in
            if let errorMessage = newValue, !errorMessage.isEmpty {
                showToast = true
                DispatchQueue.main.asyncAfter(deadline: .now() + 1) {
                    showToast = false
                    message = nil
                }
            }
        }
        .toast(isPresented: $showToast) {
            ShowMessageView(message: message)
           /* ToastView(message ?? "")
                .foregroundColor(.white)
                .background(Color.black.opacity(0.8))
                .cornerRadius(8)
                .edgesIgnoringSafeArea(.all) */
        }
        .disabled(isCounting)
        .onDisappear { timer?.invalidate() } // 视图消失时停止计时器
    }
    
    private func startCountdown() {
        isCounting = true
        countdown = 60
        timer = Timer.scheduledTimer(
            withTimeInterval: 1,
            repeats: true
        ) { _ in
            if countdown > 0 {
                countdown -= 1
            } else {
                timer?.invalidate()
                isCounting = false
            }
        }
    }
}

